﻿Imports System.IO
Imports NewHeaderSystems.Archive.Data
Imports NewHeaderSystems.Archive.Types

Public Class MatchProcessor

    ''' <summary>
    ''' Prepares the system for archiving by clearing the Matches table.
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub New()
        DataScript.ClearMatchTable()
    End Sub
    ''' <summary>
    ''' Load match table from APL Match file, update securities and accounts tables (both reference tables)
    ''' </summary>
    ''' <param name="matchFile">The path to the match file</param>
    ''' <remarks></remarks>
    Public Sub Process(ByVal matchFile As String)
        BackgroundReporter.MessagePrefix = Path.GetFileName(matchFile)
        Dim iAccountIDStartPos, iAccountIDLength, iAccountNameStartPos As Integer

        ' process match file

        '   If sysObj.AccountIdType = "BWNUM" Then
        '       iAccountIDStartPos = 164
        '       iAccountIDLength = 10
        '   Else
        iAccountIDStartPos = 157
        iAccountIDLength = 6
        iAccountNameStartPos = 174


        Dim reader As New StreamReader(New FileStream(matchFile, FileMode.Open, FileAccess.Read))
        Dim line As String
        line = reader.ReadLine()
        If Not line Is Nothing And line.Contains("TRADES FROM DTC") Then

            line = reader.ReadLine()

            Do While Not line Is Nothing
                Dim sAccountID = Trim(Mid(line, iAccountIDStartPos, iAccountIDLength))
                Dim sAccountName = Trim(Mid(line, iAccountNameStartPos))
                Dim sCustodianID = Trim(Mid(line, 48, 12))
                Dim sTicker = Trim(Mid(line, 120, 6))
                Dim sCusip = Trim(Mid(line, 61, 9))
                Dim sDescription = Trim(Mid(line, 127, 25))
                sDescription = Replace(sDescription, "+", "")

                Dim match As New Match
                match.ControlNum = Trim(Mid(line, 6, 9))
                '& Mid(sLineText, 16, 1))
                match.ControlType = Mid(line, 16, 1)
                match.AccountID = sAccountID
                match.TradeDate = Trim(Mid(line, 18, 8))
                match.Ticker = sTicker
                match.CUSIP = sCusip
                match.TxnType = Trim(Mid(line, 71, 2))
                match.Status = Trim(Mid(line, 154, 2))
                BackgroundReporter.ReportProgress(match.ToString())
                DataScript.InsertMatch(match)

                If (sAccountID <> "" And sAccountName <> "") Then ' add acount ?
                    DataScript.CheckAndInsertAccount(sAccountID, sAccountName, sCustodianID)
                End If
                If (sTicker <> "" And sCusip <> "") Then ' add security ?
                    DataScript.CheckAndInsertSecurity(sTicker, sCusip, sDescription)
                End If
                line = reader.ReadLine()
            Loop
        End If
        reader.Close()
    End Sub

End Class
